package data_structures_and_algorithms.list_node;

import common.ListNode;

/**
 * @ClassName Code_0002_addTwoNumbers
 * @Description: https://leetcode.cn/problems/add-two-numbers/
 * @Author: myl
 * @create_time: 2022/10/26 23:44
 */
public class Code_0002_addTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode cur = head, next = null;
        int carry = 0;

        while (l1 != null && l2 != null){
            int val = l1.val + l2.val + carry;
            cur.next = new ListNode(val % 10);
            carry = val / 10;

            l1 = l1.next;
            l2 = l2.next;
            cur = cur.next;
        }
        while (l1 != null){
            int val = l1.val + carry;
            cur.next = new ListNode(val % 10);
            carry = val / 10;

            l1 = l1.next;
            cur = cur.next;
        }

        while (l2 != null){
            int val = l2.val + carry;
            cur.next = new ListNode(val % 10);
            carry = val / 10;

            l2 = l2.next;
            cur = cur.next;
        }

        if (carry > 0){
            cur.next = new ListNode(carry);
        }

        return head.next;
    }


}
